//
//  SHQuickPayViewController.m
//  JiFengDaRen
//
//  Created by CYF on 2017/1/17.
//  Copyright © 2017年 SH_iOS. All rights reserved.
//
#import "CYFRSA.h"
#import "HBRSAHandler.h"
//#import "SHCasherCenterController.h"
#import "SHQuickPayViewController.h"
#import "NSDictionary+NSString.h"
#import "UserModel.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "MyOrderViewController.h"

#import "SHCashUnionPaymentController.h"


@interface SHQuickPayViewController ()<UIWebViewDelegate>
@property(strong,nonatomic)UIWebView *webView;

@end

@implementation SHQuickPayViewController


-(void)viewWillAppear:(BOOL)animated{
    [super viewDidLoad];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self configUI];
   

    
    
}
#pragma mark -- 初始化UI
- (void)configUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0,KScreenWidth,KScreenHeight)];
    //设置代理
    _webView.delegate = self;
    //缩放整个scrollview
    _webView.scalesPageToFit = YES;

    UIBarButtonItem *shut = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStyleDone target:self action:@selector(shutWebView)];
    [shut setTitleTextAttributes:@{NSFontAttributeName:KSystemFont(__I6Width(15))} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItems = @[shut];
    [self webviewRequest];
    [self.view addSubview:self.webView];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
}

- (void)shutWebView{
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -- 重新返回按钮
-(void)back:(UIBarButtonItem *)backItem{
    
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark - webview 开始请求
- (void)webviewRequest{

    switch (self.requestType) {
        case SHQuickPayWebViewRequestTypeUrl:
        {
            NSURL *url = [NSURL URLWithString:self.url];//创建URL
            NSURLRequest* request = [NSURLRequest requestWithURL:url];//创建
            [self.webView loadRequest:request];//加载
        }
            break;
            
        case SHQuickPayWebViewRequestTypeHtmlPage:
        {
            self.title = @"银联支付";
            NSString * html = [self URLDecodedString:self.page];
            [self.webView loadHTMLString:html baseURL:nil];
        }
            break;
            
        case SHQuickPayWebViewRequestTypeHtml:
        {
            self.title = @"银联支付";
            [self.webView loadHTMLString:self.page baseURL:nil];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark - WebViewDelegate
//加载失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"快捷支付网页加载失败%@",error.localizedDescription);
    [MBProgressHUD hideHUDForView:self.view animated:YES];

}

//网页加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
     SHLog(@"加载成功！");
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    SHLog(@"webView location = '%@'", webView.request.URL.absoluteString);
    //定义好JS要调用的方法, share就是调用的share方法名
    //分享app
    context[@"shareOrder"] = ^() {
        
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            
            SHLog(@"%@", jsVal.toString);
        }
        
        SHLog(@"-------End Log-------%@",args);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });

    };
    //返回
    context[@"closeActivity"] = ^() {
        
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            
            SHLog(@"%@", jsVal.toString);
        }
       
        dispatch_async(dispatch_get_main_queue(), ^{
            for (UIViewController *vc in self.rt_navigationController.rt_viewControllers) {
                if ([vc isKindOfClass:[SHCashUnionPaymentController class]]) {
                    [self.navigationController popToViewController:vc animated:YES];
                    break;
                }
            }
        });
    };
    
    //返回
    context[@"back"] = ^() {
        
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            
            SHLog(@"%@", jsVal.toString);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.navigationController popViewControllerAnimated:YES];
        });
    };

    
    //查看订单
    context[@"checkOrder"] = ^() {
        
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            
            SHLog(@"%@", jsVal.toString);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.navigationController pushViewController:[[MyOrderViewController alloc]init] animated:YES];
        });
    };

    
    //跳转到
    context[@"bindDevice"] = ^() {
        
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            SHLog(@"%@", jsVal.toString);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{

        });
        
    };
    
    //sqPaySuccess() 跳转到主页 sqPayFailure() 跳转到前一个画面
    context[@"sqPaySuccess"] = ^() {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            for (UIViewController *vc in self.rt_navigationController.rt_viewControllers) {
                if ([vc isKindOfClass:[SHCashUnionPaymentController class]]) {
                    [self.navigationController popToViewController:vc animated:YES];
                    break;
                }
            }
        });
        
    };
    
    context[@"sqPayFailure"] = ^() {

        dispatch_async(dispatch_get_main_queue(), ^{
            for (UIViewController *vc in self.rt_navigationController.rt_viewControllers) {
                if ([vc isKindOfClass:[SHCashUnionPaymentController class]]) {
                    [self.navigationController popToViewController:vc animated:YES];
                    break;
                }
            }
        });
        
    };
    
}


//转码方法

- (NSString*)URLDecodedString:(NSString*)str{
    NSMutableString *outputStr = [NSMutableString stringWithString:str];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
}


@end
